/* eslint-disable @typescript-eslint/no-explicit-any */
import { Right, Tips } from '@nutui/icons-react';
import { Address, Button, Form, Image, Input, Picker, Toast } from '@nutui/nutui-react';
import { useRequest } from 'ahooks';
import { find, get } from 'lodash-es';
import province from 'province-city-china/dist/data.json';
import level from 'province-city-china/dist/level.json';
import { forwardRef, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import { commonApi } from '@/application/apis/home';
import { ROUTE_MAP } from '@/application/constants/routerMap';
import Storage from '@/application/utils/storage';
// eslint-disable-next-line react/display-name
const AddressForm = forwardRef((props: any) => {
  const addressRef = useRef<any>(null);
  const text = useMemo(() => {
    if (!props.value) return [];

    return props.value
      .map((item: any) => item.name)
      .filter((item: any) => item != '-')
      .join(',');
  }, [props.value]);
  const val = useMemo(() => {
    if (!props.value) return [];

    return props.value.map((item: any) => item.code);
  }, [props.value]);

  return (
    <>
      <div className="flex items-center justify-center">
        <Input
          readOnly
          onClick={() => addressRef.current?.open()}
          value={text}
          placeholder="省、市、区"
        />
        <Right className="!h-3 !w-3" />
      </div>
      <Address
        value={val}
        ref={addressRef}
        defaultVisible={false}
        options={level as any}
        onChange={(value: any) => {
          const all = value.map((e: any) => find(province, (item) => item['code'] === e));
          props.onChange(all);
        }}
        onClose={() => addressRef.current?.close()}
        optionKey={{
          textKey: 'name',
          valueKey: 'code',
          childrenKey: 'children'
        }}
      />
    </>
  );
});

export default function ExchangeProduct() {
  const [form] = Form.useForm();
  const { data: address } = useRequest(commonApi.addressList, {
    onSuccess(data: any) {
      if (data && data.length > 0) {
        const res = data[0];
        form.setFieldsValue({
          ...res,
          region: [
            { code: res.provinceCode, name: res.provinceName },
            { code: res.cityCode, name: res.cityName },
            { code: res.countyCode, name: res.countyName }
          ]
        });
      }
    }
  });
  const navigate = useNavigate();

  const product = Storage.exchangeProduct.get();
  const submitSucceed = async (values: any) => {
    const addressParams = {
      ...values,
      address: values.address,
      cityCode: get(values, 'region.[1].code') || '-',
      cityName: get(values, 'region.[1].name') || '-',
      townCode: '-',
      townName: '-',
      provinceCode: get(values, 'region.[0].code') || '',
      provinceName: get(values, 'region.[0].name') || '',
      countyCode: get(values, 'region.[2].code') || '-',
      countyName: get(values, 'region.[2].name') || '-'
    };
    if (address && address.length > 0) {
      await commonApi.updateUserAddress(addressParams);
    } else {
      await commonApi.addUserAddress(addressParams);
    }
    navigate(ROUTE_MAP.AWARD_LIST, { replace: true });
  };
  return (
    <div>
      <div className="flex h-7.5 items-center bg-[#F0FFB1] px-3.75 text-xs text-[#333333]">
        <Tips className="mr-2" />
        兑换后将寄送到该地址，请确保地址正确
      </div>
      <div className="flex flex-col items-center pb-5 pt-3.75">
        <Image className="h-32.5 w-32.5 !rounded-xl" src={product?.pic} />
        <div className="mt-3.75 text-[#222]">{product?.name}</div>
      </div>
      <Form
        form={form}
        onFinish={(values) => submitSucceed(values)}
        labelPosition="right"
        footer={
          <>
            <Button
              nativeType="submit"
              block
              type="primary"
              className="h-[45px] w-full rounded-[22px] !bg-gradient-to-r from-[#FE4F05] to-[#FF8A10]  font-semibold text-white"
            >
              确定
            </Button>
          </>
        }
      >
        <Form.Item
          label="收件人"
          name="recipient"
          rules={[{ required: true, message: '请输入收件人姓名' }]}
        >
          <Input className="nut-input-text" placeholder="请输入收件人姓名" type="text" />
        </Form.Item>
        <Form.Item
          label="联系电话"
          name="mobile"
          rules={[{ required: true, message: '请输入收件人联系电话', len: 11 }]}
        >
          <Input className="nut-input-text" placeholder="请输入收件人联系电话" maxLength={11} />
        </Form.Item>
        <Form.Item label="地址选择" name="region">
          <AddressForm className="nut-input-text" />
        </Form.Item>
        <Form.Item
          label="详细地址"
          name="address"
          rules={[{ required: true, message: '请输入详细的地址' }]}
        >
          <Input className="nut-input-text" placeholder="请输入详细的地址" maxLength={100} />
        </Form.Item>
      </Form>
    </div>
  );
}
